package com.moxingzhegroup.presenter;

import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.moxingzhegroup.Constants;
import com.moxingzhegroup.base.BaseSearch;
import com.moxingzhegroup.base.IBasePresenter;
import com.moxingzhegroup.entity.Advertisement;
import com.moxingzhegroup.entity.api.PageInfo;
import com.moxingzhegroup.entity.api.Result;
import com.moxingzhegroup.presenter.callback.IVideoCallback;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author LiaoRun
 */
public class VideoPresenter implements IBasePresenter<IVideoCallback> {

    private static final String TAG = VideoPresenter.class.toString();
    private IVideoCallback mCallback;


    public VideoPresenter() {

    }

    public void downloadVideos(Advertisement videoFile, Context context) {

        Log.d(TAG, "downloadVideos: 下载了一次视频");

        if (videoFile.getStatus() == 2L) {

            Log.d(TAG, "downloadVideos: 删除的视频不要下载播放");
            return;
        }

        // 拼凑下载视频的URL

        Log.d(TAG, "downloadVideos: " + videoFile);

        Uri uri = Uri.parse(videoFile.getAdvertisementUrl());

        // 创建下载视频的Request对象
        DownloadManager.Request request = new DownloadManager.Request(uri);

        //通知栏的标题
        request.setTitle(videoFile.getName());
        //显示通知栏的说明
        request.setDescription(videoFile.getSize() + videoFile.getStatus());
        request.setVisibleInDownloadsUi(true);

        // 下载过程和下载完成后通知栏有通知消息。
        // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        // 设置下载地址
        request.setDestinationInExternalPublicDir("/myVideo", videoFile.getName());

        // 获取下载管理器
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        //下载的唯一标识，可以用这个标识来控制这个下载的任务enqueue（）开始执行这个任务
        assert downloadManager != null;

        // 下载之前删除之前所有下载失败的下载任务,防止一大堆的失败任务重新下载导致的调度问题影响性能
        DownloadManager.Query query = new DownloadManager.Query();

        query.setFilterByStatus(DownloadManager.STATUS_RUNNING);
        Cursor cursor = downloadManager.query(query);

        // 遍历删除所有的下载失败的下载任务
        while (cursor.moveToNext()) {
            downloadManager.remove(cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
            Log.d(TAG, "downloadVideos: 删除一个失败的下载任务：" + cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)));
        }

        long enqueue = downloadManager.enqueue(request);

        // 足够下载，通知等待下载完成
        if (mCallback != null) {
            mCallback.onNewVideoFileBeginDownload(enqueue, videoFile.getName());
        }

    }

    /**
     * 同步服务器的广告信息
     */
    public void getAdvertisementInfo() {
        String url = Constants.BASE_URL + "/advertisement/select";
        OkHttpClient okHttpClient = new OkHttpClient();

        Gson gson = new Gson();


        String json = gson.toJson(new BaseSearch(false, 1, 1, "sort"));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure: 获取所有的广告信息失败" + e.getMessage());

                if (mCallback != null) {
                    mCallback.onNetworkError(e.getMessage());
                }
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {

                if (response.isSuccessful()) {
                    TypeToken<Result<PageInfo<Advertisement>>> typeToken = new TypeToken<Result<PageInfo<Advertisement>>>() {
                    };

                    try {
                        assert response.body() != null;
                        Result<PageInfo<Advertisement>> pageInfoResult = gson.fromJson(response.body().string(), typeToken.getType());

                        if (pageInfoResult.code == 0) {
                            Log.d(TAG, "onResponse: 获取所有的广告信息成功");

                            // 能拿到信息就按顺序播放，拿不到就随机播放
                            if (mCallback != null) {
                                mCallback.onAllAdvertisementLoad(pageInfoResult.getData().getList());
                            }
                        } else {
                            Log.d(TAG, "onResponse: 获取所有的广告信息失败" + pageInfoResult.getMsg());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.d(TAG, "onResponse: 获取所有的广告信息失败 接口的数据格式转换失败");
                    }
                }
            }
        });
    }


    @Override
    public void registerViewCallback(IVideoCallback callback) {
        mCallback = callback;
    }

    @Override
    public void unRegisterViewCallback(IVideoCallback callback) {
        mCallback = null;
    }
}
